package com.example.leetdemo.consistenthash;

import java.io.*;
import java.util.SortedMap;
import java.util.TreeMap;


/**
 * 地址重分配
 */
public class ConsistentHashDemo {

    private static final SortedMap<Integer, String> urlHash = new TreeMap<>();

    static {
        System.err.println("1125".hashCode());
        String[] urls = new String[] {"1125", "1142", "4314", "7524"};
        for (String serverUrl: urls) {
            urlHash.put(Math.abs(serverUrl.hashCode() % 10), serverUrl);
        }
    }

    public void printlnValue(String key) {
        SortedMap<Integer, String> tailMap = urlHash.tailMap(Math.abs(key.hashCode() % 10));
        Integer firstKey;
        if (tailMap.size() == 0) {
            firstKey = urlHash.firstKey();
        } else {
            firstKey = tailMap.firstKey();
        }
        System.err.println(urlHash.get(firstKey));
    }

    public static void main(String[] args) throws FileNotFoundException {
        ConsistentHashDemo consistentHashDemo = new ConsistentHashDemo();
        String[] url = new String[] {
                "2539", "2", "1225", "23244", "2854", "25", "1534", "25634", "1199"
        };
        for (int i = 0; i < url.length; i++) {
            consistentHashDemo.printlnValue(url[i]);
        }
//        urlHash.remove("1125".hashCode());
        urlHash.put(Math.abs("1199".hashCode() % 10), "1199");
        System.err.println();
        for (int i = 0; i < url.length; i++) {
            consistentHashDemo.printlnValue(url[i]);
        }
    }
}
